package com.ldw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ldw.common.ErrorCode;
import com.ldw.mapper.SysUserMapper;
import com.ldw.pojo.SysUser;
import com.ldw.service.SysUserService;
import com.ldw.utils.JWTUtils;
import com.ldw.vo.LoginUserVo;
import com.ldw.vo.Result;
import com.ldw.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.transform.sax.TemplatesHandler;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper SysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public SysUser queryAuthorById(Long id) {
        return SysUserMapper.queryAuthorById(id);
    }

    public Result queryUserBytoken(String token) {
        /*
        1.token合法性校验， 是否为空，解析是否功能， redis是否存在
        2.如果校验失败，返回错误
        3.如果成功，返回对应的结果 LoginUserVo
         */
        if (StringUtils.isBlank(token)) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return Result.success(sysUser);
    }

    public SysUser queryUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, account);
        SysUser sysUser = SysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }

    @Override
    public UserVo queryUserVoById(Long authorId) {
        SysUser sysUser = SysUserMapper.selectById(authorId);
        UserVo userVo = new UserVo();
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setAvatar("/static/img/logo.b3a48c0.png");
            sysUser.setId(1L);
            sysUser.setNickname("喵星人");
        }
        BeanUtils.copyProperties(sysUser, userVo);
        return userVo;
    }


}
